package com.trg.designmodel.singleleton;

/**
 * @ClassName: SingleLetonTest04
 * @Description: 单例设计模式-懒汉式（线程安全-同步方法）
 * @Author: tangrg
 * @Date: 2021/6/30 15:55
 * @Version: 1.0
 * @Return:
 **/
public class SingleLetonTest04 {

    public static void main(String[] args) {
        SingleLeton04 instance = SingleLeton04.getInstance();
        SingleLeton04 instance2 = SingleLeton04.getInstance();
        System.out.println(instance == instance2);
        System.out.println("instance:" + instance.hashCode());
        System.out.println("instance2:" + instance2.hashCode());
    }
    
}

class SingleLeton04 {
    //***1、私有化构造器
    private SingleLeton04() {
    }

    private static SingleLeton04 instance;

    /**
     * 由于该方法被线程所共享，所以会存在线程安全的问题，在方法上加入同步处理的代码synchronized，解决线程的安全问题
     * @return
     */
    public static synchronized SingleLeton04 getInstance() {
        if (instance == null) {
            instance = new SingleLeton04();
        }
        return instance;
    }
}
